/**
 * jqGrid扩展
 */
(function ($) {
    var gridDefaultConfig = {
        urlPrefix: $.getProjectName(),
        showPager: true,
        datatype: "local",
        mtype: "post",
        headertitles: true,
        //height: '100%',
        altRows: true,
        altclass: 'odd',
        scrollrows: true,
        autoScroll: true,
        shrinkToFit: false,
        multiselect: true,
        viewrecords: true,
        rowNum: 20,
        rowList: [20, 50, 100],
        groupHeader: false,
        autoSetHeightWidth: true,//自动根据父高度宽度计算高度宽度（如果已经设置了宽度和高度就不计算）
        jsonReader: {
            root: "obj.rows",
            page: "obj.page",
            total: "obj.total",
            records: "obj.records"
        },
        cmTemplate: {
            sortable: false,
            align: "left"
        },
        loadComplete: function (data) {
            if (data.success === false) {

                if (data.msgType == '1') {
                    window.parent.location = $.getProjectName() + '/logon/commonQuit.htm';
                }
                if (data.msgType == '2' && data.msg) {
                    $.messager.alert("警告", data.msg, "warning");
                }
                if (data.msgType == '3' && data.msg) {
                    $.messager.alert("错误", data.msg, "error");
                }
            }
        }
    };

    /**
     * 设置列根据配置的dict进行格式化显示
     * @param {Object}colModel
     * @returns {number} 要显示列的总宽度
     */
    function setDictModel(colModel) {
        var totalWidth = 20;
        $.each(colModel, function (index, item) {

            if (item && item.dict) {
                item.formatter = function (value) {
                    if (value == null || value == '') {
                        return '';
                    }
                    var dictArr = window.parent.GLOBAL_PARAMS.DICT_CACHE[item.dict];
                    if ($.isArray(dictArr)) {
                        $.each(dictArr, function (i, data) {
                            if (data.key == value) {
                                value = data.value;
                                return false;
                            }
                        });
                    }
                    return value;
                };
                item.unformat = function (value) {
                    return value;
                };
            }

            if (item && item.hidden !== true) {
                totalWidth += typeof item.width === 'number' ? item.width + 5 : 105;
            }
        });
        return totalWidth;
    }

    /**
     * 获取有权限显示的列
     * @param {HTMLElement} el
     * @param {string} tableId
     */
    function getAuthField(el, tableId) {
        var _t = el;
        $.ajaxExt({
            url: "/sysAuthorityFunc/getAuthField.htm",
            data: {tableId: tableId}
        }).done(function (result) {
            if (result) {
                var showClos = [];
                $.each(result, function (index, item) {
                    $(_t).jqGrid('setLabel', item.fieldName, item.fieldDsc);
                    showClos.push(item.fieldName);
                });
                $(_t).jqGrid('showCol', showClos);
                _t = null;
            }
        });
    }

    $.fn.grid = function (options) {
        if (typeof options === 'string') {
            var fn = $.jgrid.getMethod(options);
            if (!fn) {
                throw ("jqGrid - No such method: " + options);
            }
            var args = $.makeArray(arguments).slice(1);
            return fn.apply(this, args);
        }


        return this.each(function () {
            var ts = this;
            options = $.extend({}, gridDefaultConfig, options);
            if (options.url) {
                options.url = options.urlPrefix + options.url;
            }

            if (options.showPager) {
                var pagerId = ts.id + '_pager';
                $('<div id="' + pagerId + '" style="background-color: white;border: none;"></div>').insertAfter(ts);
                options.pager = "#" + pagerId;
            } else {
                options.jsonReader = {
                    root: "obj"
                };
                options.rowNum = 99999;
            }

            var totalWidth = setDictModel(options.colModel);

            var exceptHeight = 35;//一行题头的高度33+border-top和border-bottom
            if (options.pager) {//翻页行高度
                exceptHeight += 32;
            }
            if (options.footerrow) {//总计行高度
                exceptHeight += 21;
            }

            if (options.groupHeader) {//一行题头的高度还要额外减去
                exceptHeight += 23;
            }

            var $parent = $(ts).parent();

            var exceptWidth = 2;//border-left、border-right

            if (!options.width) {
                options.width = $parent.width() - exceptWidth;
            } else if ($.isNumeric(options.width)) {
                options.width -= exceptWidth;
            }

            if (!options.height) {
                options.height = $parent.height() - exceptHeight;
            } else if ($.isNumeric(options.height)) {
                options.height -= exceptHeight;
            }

            options.exceptHeight = exceptHeight;

            //配置了tableId就把所有的列都隐藏掉
            //请求后台以显示相关列和列名
            if (options.tableId) {
                options.cmTemplate.hidden = true;
                getAuthField(this, options.tableId);
            } else {
                //如果显示列的总宽度小于Grid的宽度并且shrinkToFit为false就把shrinkToFit置为true以是的列填满整个grid
                if (options.shrinkToFit === false && options.width && totalWidth < options.width) {
                    options.shrinkToFit = true;
                }
            }

            if ($parent.attr('data-layout')) {
                $parent.on('can-resize', function () {
                    $(ts).jqGrid('setGridWidth', $(this).width() - exceptWidth);
                    $(ts).jqGrid('setGridHeight', $(this).height() - exceptHeight);
                });
            }

            $(ts).jqGrid(options);
        })
    };

    $.jgrid.extend({
        resize: function () {
            var _t = this;
            var $parent = $(_t).closest('.ui-jqgrid').parent();
            var width = $parent.width() < _t.getGridParam().width ? $parent.width() : $parent.width() - 2;
            $(_t).jqGrid('setGridHeight', $parent.height() - _t.getGridParam().exceptHeight);
            $(_t).jqGrid('setGridWidth', width, _t.getGridParam().shrinkToFit);
        }
    });

    $.jgrid.extend({
        /**
         * 获取第一个选中行的记录
         * @returns {*}
         */
        getSelected: function () {
            var selectRowId = this.getGridParam().selrow;
            if (selectRowId !== null) {
                return this.getRowData(selectRowId);
            }
            return null;
        },
        /**
         * 获取选中行的记录
         * @returns {Array}
         */
        getSelections: function () {
            var selectRowIds = this.getGridParam().selarrrow,
                returnArr = [],
                ts = this;
            $.each(selectRowIds, function (index, item) {
                returnArr.push(ts.getRowData(item));
            });
            return returnArr;
        },
        setGridParam: function (newParams) {
            return this.each(function () {
                if (newParams.postData) {//修复有些参数值为数组不能覆盖的问题
                    for (var prop in newParams.postData) {
                        this.p.postData[prop] = newParams.postData;
                    }
                }
                if (this.grid && typeof newParams === 'object') {
                    $.extend(true, this.p, newParams);
                }
            });
        }
    });


})
(jQuery);

/**
 * jqGrid数据格式化
 */
(function ($) {

    /**
     *触发 行中自定义按钮的自定义事件
     * @param act
     */
    $.fn.fmatter.customEvents = function (act, index) {
        var $tr = $(this).closest("tr.jqgrow"),
            rid = $tr.attr("id"),
            $id = $(this).closest("table.ui-jqgrid-btable").attr('id').replace(/_frozen([^_]*)$/, '$1'),
            $grid = $("#" + $id),
            $t = $grid[0],
            p = $t.p,
            cm = p.colModel[$.jgrid.getCellIndex(this)],
            op = {};

        if (cm.formatoptions !== undefined) {
            op = $.extend(op, cm.formatoptions);
        }

        var rowData = $grid.jqGrid('getRowData', rid);

        switch (act) {
            case 'click':
                if (typeof  op.clickFn === "function") {
                    op.clickFn.call(this, rowData);
                }
                break;
            case 'operClick':
                if (typeof  op[index].click === "function") {
                    op[index].click.call(this, rowData);
                }
                break;
        }
    };

    $.fn.fmatter.customCurrency = function (cellVal, options, rowObject, act) {
        var defaultOptions = {
            css: '',
            currency: true,
            clickFn: null
        };

        var returnHtml = "";

        if (cellVal || cellVal === 0) {
            var op = $.extend(defaultOptions, options.colModel.formatoptions);
            var valStr = cellVal.toString(),
                valSplit = valStr.split('.');
            if (op.currency) {
                if (/^\d+$/.test(valSplit)) {
                    if (valSplit.length > 1) {
                        cellVal = valSplit[0].replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") + '.' + valSplit[1];
                    } else {
                        cellVal = valSplit[0].replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
                    }
                }
            }
            if (op.clickFn) {
                if (act === 'add') {
                    if (op.clickFn) {
                        returnHtml = '<a class="{0}" onclick="$.fn.fmatter.customEvents.call(this,\'click\')">{1}</a>'.format(op.css, cellVal);
                    } else {
                        returnHtml = '<a class="{0}">{1}</a>'.format(op.css, cellVal);
                    }
                } else {
                    returnHtml = cellVal;
                }
            } else {
                return cellVal;
            }
        }
        return returnHtml;
    };
    $.fn.fmatter.customCurrency.unformat = function (cellVal) {
        var value = cellVal.replace(/,/g, '');
        if (/^\d+(\.{0,1})\d+$/.test(value)) {
            return ~~Number(value);
        }
        return value;
    };

    $.fn.fmatter.currency.unformat = function (cellVal) {
        return ~~Number(cellVal.replace(/,/g, ''));
    };


    /**
     * 操作按钮以自定义的形式展现
     * @param cellVal
     * @param options
     * @param rowObject
     * @param act
     * @returns {String} HTML字符串格式
     */
    $.fn.fmatter.operArea = function (cellVal, options, rowObject, act) {
        var h = '';
        $.each(options.colModel.formatoptions, function (i, op) {
            if (op.rule) {
                if (!op.rule(rowObject)) {
                    return;
                }
            }
            h += '<a title="" onclick="jQuery.fn.fmatter.customEvents.call(this,\'operClick\',{0})" {1} class="operate {2}">{3}</a>'.format(i, i > 0 ? 'style="margin-left:8px;"' : '', op.css || '', op.text);
        });
        return h;
    };

    $.fn.fmatter.operArea.unformat = function () {
        return '';
    };
})(jQuery);